﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Web.Services;
using System.Web.Services.Protocols;
using NPSoft.Ferrero.Framework.DAL;
using NPSoft.Ferrero.Framework.Utility;

namespace NPSoft.Ferrero.Framework.MailService
{
    /// <summary>
    /// Summary description for WCNMailService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WCNMailService : System.Web.Services.WebService
    {
        private const string EX_D = "EX_D";
        private const string EX_D_AFTER_DC = "EX_D After DC";
        private const string EX_D_MONTH_CLOSE = "EX_D Month Close";
        private string template = @"Dear Team,</BR>
                            Totally {0} {1} information record(s) received 
                            from WinChannel interface: {2} record(s) imported into local IT system successfully, 
                            {3} record(s) imported unsuccessfully.";

        public NPSoapHeader soapheader = new NPSoapHeader();

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">标识</param>
        /// <param name="to">收件人</param>
        /// <param name="identifier">标识符</param>
        /// <returns>执行结果提示信息</returns>
        [WebMethod]
        [SoapHeader("soapheader")]
        public string SendMail(string key, int identifier)
        {
            NPMessage result = new NPMessage();
            string str = string.Empty;
            if (soapheader.isValid(key, out str))
            {
                BusinessIdentifier id = BusinessIdentifier.NONE;
                string businessName = string.Empty;
                string subject = "{0} Excute Result_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                string[] strTos = this.To.Split(';');
                string[] strCcs = this.Cc.Split(';');

                List<MailAddress> tos = new List<MailAddress>();
                List<MailAddress> ccs = new List<MailAddress>();
                MailHelper mail = new MailHelper();
                mail.Account = this.Account;
                mail.Password = this.Password;
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(mail.Account, "FerreroAzure");

                for (int i = 0; i < strTos.Length - 1; i++)
                {
                    string to = strTos[i];
                    // To Address Validation
                    if (!NPValidator.IsEmail(to) || string.IsNullOrEmpty(to))
                    {
                        result.Success = false;
                        result.Add("收件人地址无法识别为有效的邮箱地址！");
                    }
                    else
                    {
                        tos.Add(new MailAddress(to));
                    };
                }

                for (int i = 0; i < strCcs.Length - 1; i++)
                {
                    string cc = strCcs[i];
                    // CC Address Validation
                    if (!string.IsNullOrEmpty(cc) && !NPValidator.IsEmail(cc))
                    {
                        result.Success = false;
                        result.Add("抄送地址无法识别为有效的邮箱地址！");
                    }
                    else if (!string.IsNullOrEmpty(cc))
                    {
                        ccs.Add(new MailAddress(cc));
                    };
                }


                try
                {
                    // 读取数据库生成DataTable
                    DataTable dt_right = new DataTable();
                    DataTable dt_error = new DataTable();
                    DataTable dt_total = new DataTable();

                    if (Enum.TryParse<BusinessIdentifier>(identifier.ToString(), out id))
                    {
                        dt_right = this.GetDailySalesIncrementData(id);
                        dt_error = this.GetDailySalesErrorData(id);
                        dt_total = this.GetDailySalesTotalData(id);
                        switch (id)
                        {
                            case BusinessIdentifier.DailySales:
                                businessName = EX_D;
                                break;
                            case BusinessIdentifier.DailySalesDC:
                                businessName = EX_D_AFTER_DC;
                                break;
                            case BusinessIdentifier.DailySalesMC:
                                businessName = EX_D_MONTH_CLOSE;
                                break;
                        }
                    }
                    else
                    {
                        result.Success = false;
                        result.Add("不明确的业务标识符！");
                    }

                    if (result.Success)
                    {
                        int rightcnt = 0;
                        int totalcnt = 0;
                        int errorcnt = dt_error.Rows.Count;
                        int.TryParse(dt_right.Rows[0]["CNT"].ToString(), out rightcnt);
                        int.TryParse(dt_total.Rows[0]["CNT"].ToString(), out totalcnt);

                        // 没错误不发邮件
                        if (errorcnt > 0)
                        {
                            byte[] bys = mail.GetAttachStream(dt_error);
                            if (bys != null && bys.Length > 0)
                            {
                                MemoryStream ms = new MemoryStream(bys);
                                Attachment at = new Attachment(ms, "ErrorMsg.xlsx", MediaTypeNames.Text.Plain);
                                msg.Attachments.Add(at);
                            }
                        }

                        msg.Subject = string.Format(subject, businessName);
                        msg.Body = string.Format(template, totalcnt, businessName, rightcnt, errorcnt);
                        result = mail.SendBySMTP(tos, ccs, msg);

                        msg.Attachments.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Add(ex.Message);
                }
            }
            else
            {
                result.Success = false;
                result.Message = str;
            }
            return result.Message;
        }

        /// <summary>
        /// 获取数据库连接对象
        /// </summary>
        public string ConnectionString
        {
            get
            {
                string connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["local"].ToString();
                return connString;
            }
        }

        /// <summary>
        /// 账号
        /// </summary>
        public string Password
        {
            get
            {
                string encryptPwd = ((NameValueCollection)System.Web.Configuration.WebConfigurationManager.GetSection("NewsPage/mail"))["Password"];
                return EncryptHelper.DesDecrypt(encryptPwd);
            }
        }


        /// <summary>
        /// 账号
        /// </summary>
        public string Account
        {
            get
            {
                string encryptAccount = ((NameValueCollection)System.Web.Configuration.WebConfigurationManager.GetSection("NewsPage/mail"))["Account"];
                return encryptAccount;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string To
        {
            get
            {
                string to = ((NameValueCollection)System.Web.Configuration.WebConfigurationManager.GetSection("NewsPage/mail"))["to"];
                return to;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string Cc
        {
            get
            {
                string cc = ((NameValueCollection)System.Web.Configuration.WebConfigurationManager.GetSection("NewsPage/mail"))["cc"];
                return cc;
            }
        }

        #region "WinChannel"

        #region "获取错误数据"

        /// <summary>
        /// 获取Daily Sales Error Data
        /// </summary>
        /// <returns></returns>
        public DataTable GetDailySalesErrorData(BusinessIdentifier which)
        {
            DataSet ds = new DataSet();
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@which", which);
            ds = SqlHelper.ExecuteDataset(this.ConnectionString, "usp_WCN_GetDailySalesErrorData", param);

            return ds.Tables[0];
        }

        #endregion

        #region "获取正确数据"

        /// <summary>
        /// 获取Daily Sales Increment Data
        /// </summary>
        /// <returns></returns>
        public DataTable GetDailySalesIncrementData(BusinessIdentifier which)
        {
            DataSet ds = new DataSet();
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@which", which);
            ds = SqlHelper.ExecuteDataset(this.ConnectionString, "usp_WCN_GetDailySalesIncrementData", param);

            return ds.Tables[0];
        }

        #endregion

        #region "获取正确数据"

        /// <summary>
        /// 获取Daily Sales Increment Data
        /// </summary>
        /// <returns></returns>
        public DataTable GetDailySalesTotalData(BusinessIdentifier which)
        {
            DataSet ds = new DataSet();
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@which", which);
            ds = SqlHelper.ExecuteDataset(this.ConnectionString, "usp_WCN_GetDailySalesTotalData", param);

            return ds.Tables[0];
        }

        #endregion

        #endregion

        /// <summary>
        /// 业务标识符
        /// </summary>
        public enum BusinessIdentifier
        {
            NONE = 0,
            DailySales = 1,
            DailySalesDC = 2,
            DailySalesMC = 3
        }
    }
}
